package com.yl.chainStore.services.impl

import com.yl.chainStore.services.IContextService
import com.yl.common.Flag
import com.yl.common.UserType
import com.yl.common.getContext
import com.yl.users.entity.CompanyUser
import com.yl.users.services.ICompanyUserService
import com.yl.users.services.ISysCompanyService
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service

/**
 *
 * create by 2021/5/14.
 * @author udbjqr
 */
@Service
class ContextServiceImpl(
	private val iCompanyUserService: ICompanyUserService,
	private val companyService: ISysCompanyService,
) : IContextService {
	companion object {
		private val log = LoggerFactory.getLogger(IContextService::class.java)
	}

	override val currentUser: CompanyUser
		get() {
			val context = getContext()
			if (context.userId == 0L) return ANONYMOUS_USER
			return when (context.userType) {
				UserType.Custom -> ANONYMOUS_USER
				UserType.Admin -> ANONYMOUS_USER
				UserType.Company -> {
					val company = companyService.getCompanyDetail(context.companyId)
					if (company == null) {
						log.error("当前上下文对象的企业无法得到..context{}", context)
						ANONYMOUS_USER
					}
					val user = iCompanyUserService.getUser(context.userId)
					if (user == null) {
						log.error("当前上下文对象的用户ID无效..context{}", context)
						ANONYMOUS_USER
					} else
						user
				}
				UserType.Unknown -> {
					log.error("向一个未知的用户类型请求用户对象.")
					ANONYMOUS_USER
				}
			}
		}
}

private val ANONYMOUS_USER = CompanyUser(
	id = 0,
	nickName = "匿名用户",
	realName = "匿名用户",
	flag = Flag.UNKNOWN,
	userType = UserType.Custom,
	companyId = 0
)
